﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FacturIT.Service.Project;
using FacturIT.Service.WorkingHour;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace Factur_IT.Project
{
    public partial class projectDetails : System.Web.UI.Page
    {
        int id;
        int companyid;

        DateTime van;
        DateTime tot;
        protected void Page_Load(object sender, EventArgs e)
        {
            bool loggedIn = FacturIT.Service.FacturITManager.Instance.IsLoggedID();

            if (loggedIn != true)
                Response.Redirect("~/Account/login.aspx");
            
            string projectid = Request.Params["ProjectID"];
            id = Convert.ToInt32(projectid);
            lblProject.Text = FacturIT.Service.FacturITManager.Instance.ReadProject(id).ProjectName;
            foreach (var item in FacturIT.Service.FacturITManager.Instance.ReadAllCompaniesFromProject(id))
	        {
                foreach (var my in FacturIT.Service.FacturITManager.Instance.ReadMyCompanies(Convert.ToInt32(Session["UserID"])))
                {
                    if (item.CompanyID == my.CompanyID)
                        companyid = item.CompanyID;
                }
            } 
            
            
            ProjectDTO project = FacturIT.Service.FacturITManager.Instance.ReadProject(id);
            int mycompanyprojectid = FacturIT.Service.FacturITManager.Instance.ReadCompanyProjectByProjectAndCompany(id, companyid).CompanyProjectID;

            lblProjectID.Text = project.ProjectID.ToString();
            lblName.Text = project.ProjectName;
            lblStartDate.Text = project.StartDate.ToShortDateString();
            lblEndDate.Text = project.EndDate.HasValue ? project.EndDate.Value.ToShortDateString() : "";
            
            string companies = "";
            foreach (var item in FacturIT.Service.FacturITManager.Instance.ReadAllCompaniesFromProject(id))
            {
                companies = companies + FacturIT.Service.FacturITManager.Instance.ReadCompany(item.CompanyID).CompanyName + "<br \\>";
            }
            lblUsers.Text = companies;
            
            TimeSpan workingTime = TimeSpan.Zero;
            foreach (var item in FacturIT.Service.FacturITManager.Instance.ReadTotalWorkingHoursForProject(id))
            {
                workingTime =  workingTime + item.WorkingTime;
            }
            lblTotalWorkHours.Text = workingTime.TotalHours.ToString();

            TimeSpan myWorkingTime = TimeSpan.Zero;
            foreach (var item in FacturIT.Service.FacturITManager.Instance.ReadAllMyTotalWorkingHoursForProject(mycompanyprojectid))
            {
                myWorkingTime =  myWorkingTime + item.WorkingTime;
            }
            lblMyTotalWorkHours.Text = myWorkingTime.TotalHours.ToString();

            TimeSpan chargedHours = TimeSpan.Zero;
            foreach (var item in FacturIT.Service.FacturITManager.Instance.ReadMyTotalChargedForProject(mycompanyprojectid))
            {
                chargedHours = chargedHours + item.WorkingTime;
            }
            lblMyTotalCharged.Text = chargedHours.TotalHours.ToString();
            
            lblPaymentType.Text = FacturIT.Service.FacturITManager.Instance.ReadPaymentType(
                                                FacturIT.Service.FacturITManager.Instance.ReadPaymentTypeFromProject(id).PaymentType).Name;
        }

        protected void insertHours_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/WorkingHour/addWorkingHour.aspx?ProjectID=" + id + "&CompanyID=" + companyid);
        }

        //protected void generateInvoice_Click(object sender, EventArgs e)
        //{
        //   Response.Redirect("~/WorkingHour/generateInvoice.aspx?CompanyID=" + companyid + "&ProjectID=" + id);
        //}
        protected void generateInvoice_Click(object sender, EventArgs e)
        {
            bool status = pnlInvoice.Visible;
            pnlInvoice.Visible = !status;
        }

        protected void btnInvoice_Click(object sender, EventArgs e)
        {

            using (Document doc = new Document())
            {
                PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
                doc.Open();

                //header
                Rectangle page = doc.PageSize;
                PdfPTable head = new PdfPTable(1);
                head.TotalWidth = page.Width;
                Phrase phrase = new Phrase(DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " GMT", new Font(Font.FontFamily.COURIER, 8));
                PdfPCell c = new PdfPCell(phrase);
                c.Border = Rectangle.NO_BORDER;
                c.VerticalAlignment = Element.ALIGN_TOP;
                c.HorizontalAlignment = Element.ALIGN_CENTER;
                head.AddCell(c);
                head.WriteSelectedRows(
                    // first/last row; -1 writes all rows
                                      0, -1,
                    // left offset
                                      0,
                    // ** bottom** yPos of the table
                                      page.Height - doc.TopMargin + head.TotalHeight + 20,
                                      writer.DirectContent
                                    );

                /* add image
                 Image gif = Image.GetInstance(Request.MapPath("~/kyouyuu/image/kuujinbo2.gif"));
                 gif.Alignment = Image.MIDDLE_ALIGN;
                // downsize the image by specified percentage        
                    gif.ScalePercent(50f);
                    doc.Add(gif);
                 */
                Paragraph hoofding = new Paragraph();
                hoofding.Add(FacturIT.Service.FacturITManager.Instance.ReadCompany(companyid).CompanyName + " \n");
                hoofding.Add(FacturIT.Service.FacturITManager.Instance.ReadCompany(companyid).Street + " \n");
                hoofding.Add(FacturIT.Service.FacturITManager.Instance.ReadCompany(companyid).PostalCode + " " + FacturIT.Service.FacturITManager.Instance.ReadCompany(companyid).City + " \n");
                hoofding.Add(FacturIT.Service.FacturITManager.Instance.ReadCompany(companyid).Country + " \n");
                hoofding.Add(FacturIT.Service.FacturITManager.Instance.ReadCompany(companyid).CompanyPhone + " \n");

                doc.Add(hoofding);

                Paragraph datum = new Paragraph(DateTime.Today.ToString().Split(' ')[0]);
                datum.Alignment = 2;
                doc.Add(datum);

                Paragraph p = new Paragraph("Werkuren periode " + calVan.SelectedDate.ToString().Split(' ')[0] + " - " + calTot.SelectedDate.ToString().Split(' ')[0]);
                p.Alignment = 1;
                doc.Add(p);
                // table data, see code snippet following this one
                doc.Add(HoursTable());


                Paragraph totaal = new Paragraph();
                TimeSpan totaalUren = TimeSpan.Zero;
                int companyprojectid = FacturIT.Service.FacturITManager.Instance.ReadCompanyProjectByProjectAndCompany(id, companyid).CompanyProjectID;
                foreach (var item in FacturIT.Service.FacturITManager.Instance.ReadAllWorkingHoursFromUserProjectInPeriodAndSetCharged(companyprojectid, van, tot))
                {
                    totaalUren += item.WorkingTime;
                }
                totaal.Alignment = 2;
                totaal.Add(totaalUren.ToString());
                doc.Add(totaal);


                doc.Close();
                pnlInvoice.Visible = false;
            }
        }
        private PdfPTable HoursTable()
        {
            string[] col = { "Van", "Tot", "Aantal uren" };
            PdfPTable table = new PdfPTable(3);
            /*
            * default table width => 80%
            */
            table.WidthPercentage = 100;
            // then set the column's __relative__ widths
            table.SetWidths(new Single[] { 2, 2, 2 });
            /*
            * by default tables 'collapse' on surrounding elements,
            * so you need to explicitly add spacing
            */
            table.SpacingBefore = 10;

            for (int i = 0; i < col.Length; ++i)
            {
                PdfPCell cell = new PdfPCell(new Phrase(col[i]));
                cell.BackgroundColor = new BaseColor(204, 204, 204);
                table.AddCell(cell);
            }

            // !! database code omitted !!
            // r.Read is the DbDataReader for whatever flavor 
            // of database you're connecting to; we're iterating
            // over the results returned from the database and 
            // adding rows to the table in the PDF 

            List<WorkingHourDTO> werkuren = new List<WorkingHourDTO>();

            //int companyid = Convert.ToInt32(Session["UserID"]);
            //int projectid = Convert.ToInt32(Request.Params["ProjectID"]);
            int companyprojectid = FacturIT.Service.FacturITManager.Instance.ReadCompanyProjectByProjectAndCompany(id, companyid).CompanyProjectID;

            van = calVan.SelectedDate;
            tot = calTot.SelectedDate;

            foreach (var item in FacturIT.Service.FacturITManager.Instance.ReadAllWorkingHoursFromUserProjectInPeriodAndSetCharged(companyprojectid, van, tot))
            {
                table.AddCell(item.Starttime.ToString().Split(' ')[0]);
                table.AddCell(item.Endtime.ToString().Split(' ')[0]);
                table.AddCell(item.WorkingTime.ToString());
            }
            return table;
            
        }

    }
}